﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Model
{
    /// <summary>
    /// RESPONSABILITY: - task repository
    ///                 - create a new task
    ///                 - add a task to the list of tasks
    ///                 - delete a task
    /// </summary>
    public class TaskChange
    {
        private List<Task> tasks = new List<Task>();
        public IEnumerable<ITask> GetTasks(List<string> codes = null)
        {
            if (codes == null)
            {
                return (IEnumerable<ITask>)tasks;
            }

            var result = tasks.Where(c => codes.Contains(c.TaskCode));

            //Console.WriteLine("GetCompanies returns " + result.Count() + " results" );

            return (IEnumerable<ITask>)result;
        }

        public Task CreateTask(string taskCode, int estimatedTime, Employee employee)
        {
            if (string.IsNullOrEmpty(taskCode))
            {
                throw new ArgumentException("The task cod cannot be null", taskCode);
            }

           Task task = new Task(taskCode,estimatedTime,employee);
            this.AddTask(task);
            return task;
        }

        public void AddTask(Task task)
        {
            if (CheckTaskIDExistance(task.TaskId))
            {
                return;
            }

            if (CheckTaskCodeExistance(task.TaskCode))
            {
                throw new Exception("A employee with the code " + task.TaskCode + " already exists");
            }

            tasks.Add(task);

        }

        private bool CheckTaskCodeExistance(string code)
        {
            var _task = tasks.FirstOrDefault(t => t.TaskCode == code);

            var isFound = _task != null;

            return isFound;
        }

        private bool CheckTaskIDExistance(int id)
        {
            var _task = tasks.FirstOrDefault(e => e.TaskId == id);

            var isFound = _task != null;

            return isFound;
        }

        public void DeleteTask(Task task)
        {
            Task removeTask = tasks.FirstOrDefault(t => t.TaskId == task.TaskId);
            if (removeTask != null)
            {
                tasks.Remove(task);
            }
        }
    }
}
